package com.codefish.codefishseckill.utils;

import com.codefish.codefishseckill.utils.model.PageInfo;
import lombok.extern.slf4j.Slf4j;

/**
 * 分页工具类
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/09/01 下午 03:34
 */
@Slf4j
public class PageUtils {
    public static final int DEFAULT_PAGE_INDEX = 1;
    public static final int DEFAULT_ROW_COUNT = 5;

    public static void countFromIndex(PageInfo pageInfo) {
        if (pageInfo.getPageId() == null || pageInfo.getPageId() <= 0) {
            log.debug("pageId的值{}不合法，设置为默认值{}", pageInfo.getPageId(), DEFAULT_PAGE_INDEX);
            pageInfo.setPageId(DEFAULT_PAGE_INDEX);
        }
        if (pageInfo.getRowCount() == null || pageInfo.getRowCount() <= 0) {
            log.debug("rowCount的值{}不合法，设置为默认值{}", pageInfo.getRowCount(), DEFAULT_ROW_COUNT);
            pageInfo.setRowCount(DEFAULT_ROW_COUNT);
        }
        int index = (pageInfo.getPageId() - 1) * pageInfo.getRowCount();
        pageInfo.setFromIndex(index);
    }

    public static void countPageSize(PageInfo pageInfo) {
        if (pageInfo.getFromIndex() == null) {
            countFromIndex(pageInfo);
        }
        Integer totalCount = pageInfo.getTotalCount();
        if (totalCount == null) {
            pageInfo.setTotalCount(0);
            totalCount = 0;
        }

        int pageCount = totalCount / pageInfo.getRowCount();
        if (pageCount * pageInfo.getRowCount() < totalCount) {
            pageCount++;
        }
        pageInfo.setPageCount(pageCount);
    }
}
